// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package log

import (
	"bytes"
	"encoding/json"
	//"fmt"
	//"io/ioutil"

	"github.com/gin-gonic/gin"
)

const DefaultUser string = "-"

// 重写writer，保存返回的内容
type bodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

// 写字节
func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

// 写字符串
func (w bodyLogWriter) WriteString(s string) (int, error) {
	w.body.WriteString(s)
	return w.ResponseWriter.WriteString(s)
}

// 返回的结果，用来判断是否成功
type responseData struct {
	Success bool
}

// 中间件
func AuditLogger(c *gin.Context) {
	bodyLogWriter := &bodyLogWriter{
		body:           bytes.NewBufferString(""),
		ResponseWriter: c.Writer,
	}
	c.Writer = bodyLogWriter

	//// 获取body
	//rawBodyBytes, _ := c.GetRawData()
	//c.Request.Body.Close()
	//c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rawBodyBytes))

	//处理请求
	c.Next()

	responseBody := bodyLogWriter.body.String()

	// 判断是否成功
	response := responseData{}
	if responseBody != "" {
		json.Unmarshal([]byte(responseBody), &response)
	}

	method := c.Request.Method
	if method == "DELETE" || method == "PATCH" || method == "POST" || method == "PUT" {
		remoteAddr := c.ClientIP()
		urlPath := c.Request.RequestURI
		if response.Success {
			//// 成功时打印请求的数据
			//requestData := string(rawBodyBytes)
			//if c.Request.MultipartForm != nil {
			//    requestData = fmt.Sprintf("%v", c.Request.MultipartForm)
			//} else if len(c.Request.PostForm) > 0 {
			//    requestData = fmt.Sprintf("%v", c.Request.PostForm)
			//}

			Printf("[AIP_AUDIT] %s | %s | %s | %s | Success, data: %s",
				DefaultUser, remoteAddr, method, urlPath, responseBody)
		} else {
			Printf("[AIP_AUDIT] %s | %s | %s | %s | Operation Failed",
				DefaultUser, remoteAddr, method, urlPath)
		}
	}
}
